package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @User: vitobo
 * @Date: 2024-08-08
 * @Description:
 *  使用callable来计算 1+2+3+...+1000;
 *
 *  callable也可以用来 创建线程;
 *
 *
 */
public class ThreadDemo29 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            // call() 就相当于Runnable的run()方法, call方法的返回值是 泛型参数
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i < 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };

        // 不能直接把callable传入到Thread的构造方法里, 需要套上一层其它的辅助类;
        // FutureTask未来的一个任务,
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();

        // get获取结果, get会发生阻塞, 知道callable执行完毕, get才阻塞完成,才获取到结果;
        Integer result = futureTask.get();
        System.out.println(result);
    }
}
